// Ionic_SDK
// 
// 保佑没Bug 
//
// Created by AS on 2019/4/14. 
//
// Copyright © 2018 AS. All rights reserved.
// 

#import "PostViewController.h"
#import "UserInfo.h"
#import "MTypeModel.h"
#import "TQPickerView.h"
#import "CollectionImageCell.h"
#import "GMImagePickerController.h"
#import "TZImagePickerController.h"

@interface PostViewController ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
/**  */
//@property (nonatomic,strong) UITextField *titleText;
/**  */
@property (nonatomic,strong) UITextView *contentText;
/**  */
@property (nonatomic,strong) UserInfo *userInfo;
/**  */
@property (nonatomic,strong) UIBarButtonItem *postItem;
/**  */
@property (nonatomic,strong) UIView *contentView;
/**  */
@property (nonatomic,strong) UICollectionView *collectionView;

/**  */
@property (nonatomic,strong) NSMutableArray *imagesArray;

/**  */
@property (nonatomic,strong) NSMutableArray *selectImages;

@property(nonatomic, strong) NSMutableArray *imagePaths;
@property(nonatomic, assign) NSInteger imgIndex;

@end

@implementation PostViewController


-(NSMutableArray *)selectImages{
    if (!_selectImages) {
        _selectImages = [NSMutableArray array];
    }
    return _selectImages;
}

-(NSMutableArray *)imagesArray{
    if (!_imagesArray) {
        _imagesArray = [NSMutableArray arrayWithObject:@"add_image"];
    }
    return _imagesArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发表内容";
    self.view.backgroundColor = HexRGB(0xf3f5f5);
    self.userInfo = [UserInfo getUserInfo];
    [self initSubView];
}

-(void)initSubView{
    
    self.postItem = [[UIBarButtonItem alloc]initWithTitle:@"发表" style:UIBarButtonItemStylePlain target:self action:@selector(postAction)];
    self.postItem.enabled = NO;
    self.navigationItem.rightBarButtonItem = self.postItem;
    

    CGFloat imageHeight = (ScreenWidth - 50) / 3;

    self.contentText = [[UITextView alloc]initWithFrame:CGRectMake(0, 10, self.view.width, 150)];
    self.contentText.placeholder = @"说点什么吧...";
    self.contentText.font = Font16;
    self.contentText.contentInset = UIEdgeInsetsMake(5,10, 5, 10);
    self.contentText.textColor = HexRGB(0x222222);
    self.contentText.delegate = self;
    self.contentText.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentText];
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.contentText.maxY, self.view.width, imageHeight * 3 + 50) collectionViewLayout:[self imageLayout]];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.contentInset = UIEdgeInsetsMake(15, 15, 15, 15);
    [self.collectionView registerClass:[CollectionImageCell class] forCellWithReuseIdentifier:@"CollectionImageCell"];
    self.collectionView.backgroundColor = self.view.backgroundColor;
    [self.view addSubview:self.collectionView];
}
-(void)postAction{
    [self.view endEditing:YES];
    self.imgIndex = 0;
    self.imagePaths = [NSMutableArray array];
    if (self.selectImages.count > 0) {
        [self uploadPhotos:self.imgIndex];
        return;
    }
    [self submitAction];
}


-(void)submitAction{
    NSString *url2 = @"/api/communicationcircle/insertCommunication";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"uid"] = @(self.userInfo.uid);
    dict[@"loginToken"] = self.userInfo.loginToken;
    dict[@"title"] = @"";
    dict[@"content"] = self.contentText.text;
    dict[@"imgs"] = [self.imagePaths componentsJoinedByString:@","];
    
    [MBProgressHUD showMessage:@"发表中..." toView:self.view];
    
    [HTTPTools POST:url2 parameters:dict callback:^(id result, NSString *msg, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (!error) {
            if (!msg) {
                NSLog(@"%@",result);
                [MBProgressHUD showSuccess:@"发表成功"];
                [self popViewController];
                if ([self.delegate respondsToSelector:@selector(postViewControllerPostFinsh)]) {
                    [self.delegate postViewControllerPostFinsh];
                }
            }
        }
    }];
}

- (void)uploadPhotos:(NSInteger)imgIndex {
    NSString *url = @"/api/userinfo/uploadPhoto";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"uid"] = @(self.userInfo.uid);
    dict[@"loginToken"] = self.userInfo.loginToken;
    [MBProgressHUD showMessage:[NSString stringWithFormat:@"上传第%ld张图片",imgIndex + 1] toView:self.view];
    [HTTPTools POSTImageFile:url parameters:dict imageData:self.selectImages[imgIndex] success:^(NSDictionary *success) {
         [MBProgressHUD hideHUDForView:self.view];
        if ([success[@"status"] integerValue] == 200) {
            [self.imagePaths addObject:success[@"data"]];
            self.imgIndex ++;
            if (self.imgIndex >= self.selectImages.count) {
                [self submitAction];
            }else{
                [self uploadPhotos:self.imgIndex];
            }
        }else{
            [MBProgressHUD showError:@"上传图片失败"];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"上传图片失败"];
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

-(void)openImagePicker{
    TZImagePickerController *picker = [[TZImagePickerController alloc]initWithMaxImagesCount:9 - self.selectImages.count delegate:self];
    picker.allowPickingVideo = NO;
    [self presentViewController:picker animated:YES completion:nil];
}


-(void)refreshImage{
    [self.imagesArray removeAllObjects];
    [self.imagesArray addObjectsFromArray:self.selectImages];
    if (self.selectImages.count < 9) {
        [self.imagesArray addObject:@"add_image"];
    }
    [self.collectionView reloadData];
}
-(void)deletedSelectImage:(NSInteger)index{
    
    [self.selectImages removeObjectAtIndex:index];
    [self refreshImage];
}


-(void)titleTextChangeValue:(UITextField *)textField{
    self.postItem.enabled = self.contentText.text.length > 0;
}

-(void)textViewDidChange:(UITextView *)textView{
    self.postItem.enabled = self.contentText.text.length > 0;
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    [self.selectImages addObjectsFromArray:photos];
    [self refreshImage];

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    UIImage *image = [UIImage imageWithData:UIImageJPEGRepresentation(originalImage, 0.5)];
    [self.selectImages addObject:image];
    [self refreshImage];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imagesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionImageCell" forIndexPath:indexPath];
    [cell setImage:self.imagesArray[indexPath.item] withIndex:indexPath.item];
    WeakSelf(weakSelf);
    cell.deletedBlock = ^(NSInteger index) {
        [weakSelf deletedSelectImage:index];
    };
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    id obj = self.imagesArray[indexPath.item];
    
    if ([obj isKindOfClass:[NSString class]]) {
        
        WeakSelf(weakSelf);
        [self openAlertControllerTitle:nil message:nil style:UIAlertControllerStyleActionSheet actionTitle1:@"打开相册" actionTitle2:@"拍摄照片" callback:^(int index) {
            
            if (index == 1) {
                [weakSelf openImagePicker];
            }else if (index == 2){
                [self openImagePickerWithTarget:self withType:UIImagePickerControllerSourceTypeCamera editing:NO];
            }
        }];
    }
}




-(UICollectionViewFlowLayout *)imageLayout{
    CGFloat imageHeight = (ScreenWidth - 50) / 3;
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    layout.itemSize = CGSizeMake(imageHeight, imageHeight);
    
    return layout;
}









@end

